<?php
// +----------------------------------------------------------------------
// | Author: 发仔 <i@fazi.me> 
// +----------------------------------------------------------------------

namespace app\admin\controller;

use think\Db;
use think\Cache;
use think\file;

class Car extends Base
{
    protected $id = 'car_id';
    protected $table = 'car';

    //DATA
    protected function data() {
        $P = input('post.');

        //ID
        if( isset($P['id']) ) {
            $P[$this->id] = $P['id'];
            unset($P['id']);
        }
        //数据整理
        $P = array_map('Arr2Set',$P);
        $this->validData( $P );#验证
        $data = $this->parseData( $P );

        //数组值变SET
        if($data[$this->id]) {

        } else {
            unset($data[$this->id]);
        }
        //上传图片
        $data = $this->upload($data);

        // 组合出该车车型品牌系列
        $brand = Db::name('car_brand')->where('car_brand_id', $data['car_brand_id'])->value('name');
        $model = Db::name('car_brand')->where('car_brand_id', $data['car_model_id'])->value('name');
        $series = Db::name('car_brand')->where('car_brand_id', $data['car_series_id'])->value('name');

        $data['brand_name'] = $brand . ' ' . $model . ' ' . $series;


        return $data;
    }

    public function index() {

        $op = input('param.op');
        $filter = input('param.filter/s');

        //搜索
        $where = [];
        $car_type_id = input('param.car_type_id/d');
        $number = input('param.number');
        $name = input('param.name');
        $prop = input('param.prop');
        $entrust_company_id = input('param.entrust_company_id');
        $company_id = input('param.company_id');

        //筛选
        $filter_type = input('param.filter_type');
        if($filter_type == 1){
            $where['is_beidou'] = 1;
        } elseif($filter_type == 2) {
//			$where['is_beidou'] = 1;
            $where['entrust_company_id'] = 0;
        }

        //公司
        $car_type_id && $where['car_type_id']  = $car_type_id;
        $company_id && $where['r.company_id'] = $company_id;
        $number && $where['c.number']  = ['LIKE',"%$number%"];
        $name && $where['r.company_name']  = ['LIKE',"%$name%"];
        $entrust_company_id && $where['entrust_company_id']  = $entrust_company_id;
        $prop && $where['c.prop']  = $prop;

        $this->options($where);
        //性质
        $props = config('base.car_prop');
        $this->assign('props',TplOptions($props,$prop,'name','id'));
        //POPUP
        $this->assign('op',$op);
        if($op) {
//			$where['c.state'] = 1;
            $this->assign('notPopup',0);
        }

        $SQL = Db::name($this->table)->alias('c')
            ->join('company r','c.company_id = r.company_id','left');
        //关联
        if(in_array($op, ['bind','unbind']) ) {
            $driver_id = input('param.driver_id');
            $inornot = $op == 'bind' ? 'not in' : 'in';
            $SQL = $SQL->where('car_id',$inornot,function($query) use($driver_id) {
                $query->name('Driver')->where('driver_id',$driver_id)->field('car_id');
            });
        }

        //车型
        $list = $SQL->where($where)->where('c.delete_time','exp',  $filter == 'delete' ? 'IS NOT NULL' : "IS NULL" )->field('*')->fetchSql(0)->paginate(10,false,['query' => input('param.')  ]);
//		halt($list);
        $this->assign('list',$list);
        $this->assign('pager',$list->render());
        return $this->out();
    }

    //车辆统计
    public function stat() {

        //搜索
        /*$start = input('param.start','1970-01-01');
        $end = input('param.end',date('Y-m-d'));
        */
        $start = $start ?: '1970-01-01';
        $end = $end ?: date('Y-m-d');
        //时间段
        /*$time = input('param.time');
        if($time == 'day') {
            $start = date('Y-m-d');
        } elseif($time == 'month') {
            $start = date('Y-m-01');
        } elseif($time == 'year') {
            $start = date('Y-01-01');
        }*/
        $where = [];
        //委托车辆
        $entrust = $this->_entrust();
        $this->assign('entrust',$entrust);

        //搜索
        $number = input('param.number');
        $company = input('param.company');
        $prop = input('param.prop');
        $car_type_id = input('param.car_type_id');

        //车辆类型
        $car_types = Db::name('CarType')->whereNull('delete_time')->where('state',1)->column('car_type_name','car_type_id');
        $this->assign('car_type_ids',TplOptions($car_types,$car_type_id));
        //性质
        $props = config('base.car_prop');
        $this->assign('props',TplOptions($props,$prop,'name','id'));
        $prop && $where['prop'] = $prop;
        //筛选
        $filter = input('param.filter');
        if($filter == 1){
            $where['is_beidou'] = 1;
        } elseif($filter == 2) {
            $where['is_beidou'] = 1;
            $where['entrust_rental_id'] = 0;
            $where['entrust_use_id'] = 0;
        }
        //筛选

        $car = Db::name('car');
        $driver = Db::name('driver')->alias('m');
        $refuel = Db::name('refuel_record');#加油
        $service = Db::name('maintenance_record');#维保
        $survey = Db::name('mot_record');#年检
        $insure = Db::name('car_insure');#保险
        $order = Db::name('order');

        //车型
        if($car_type_id) {
            $car = $car->alias('c')->join('car_type ct','ct.car_type_id = c.car_type_id','left')->where('ct.car_type_id',$car_type_id);
            $driver->join('car c','c.car_id = m.car_id')->join('car_type ct','ct.car_type_id = c.car_type_id')->where('ct.car_type_id',$car_type_id);
            $refuel = $refuel->alias('m')->join('car c','c.car_id = m.car_id')->join('car_type ct','ct.car_type_id = c.car_type_id')->where('ct.car_type_id',$car_type_id)->where('m.start_date','>=',$start)->where('m.start_date','<=',$end);
            $service = $service->alias('m')->join('car c','c.car_id = m.car_id')->join('car_type ct','ct.car_type_id = c.car_type_id')->where('ct.car_type_id',$car_type_id)->where('m.start_date','>=',$start)->where('m.end_date','<=',$end);
            $survey = $survey->alias('m')->join('car c','c.car_id = m.car_id')->join('car_type ct','ct.car_type_id = c.car_type_id')->where('ct.car_type_id',$car_type_id)->where('m.start_date','>=',$start)->where('m.end_date','<=',$end);
            $insure = $insure->alias('m')->join('car c','c.car_id = m.car_id')->join('car_type ct','ct.car_type_id = c.car_type_id')->where('ct.car_type_id',$car_type_id)->where('m.start_date','>=',$start)->where('m.end_date','<=',$end);
            $order = $order->alias('m')->join('car c','c.car_id = m.car_id')->join('car_type ct','ct.car_type_id = c.car_type_id')->where('ct.car_type_id',$car_type_id)->where('m.order_time','>=',$start)->where('m.order_time','<=',$end);

        } elseif($number) {
            $car = $car->where('number','like',"%$number%");
            $refuel = $refuel->alias('m')->join('car c','c.car_id = m.car_id')->where('c.number','like',"%$number%");
            $service = $service->alias('m')->join('car c','c.car_id = m.car_id')->where('c.number','like',"%$number%");
            $survey = $survey->alias('m')->join('car c','c.car_id = m.car_id')->where('c.number','like',"%$number%");
            $insure = $insure->alias('m')->join('car c','c.car_id = m.car_id')->where('c.number','like',"%$number%");
            $order = $order->alias('m')->join('car c','c.car_id = m.car_id')->where('c.number','like',"%$number%");
        } elseif($company) {
            $car = $car->alias('c')->join('company cr','cr.company_id = c.company_id','left')->where('cr.company_name','like',"%$company%");
            $driver = $driver->alias('m')->join('car c','c.car_id = m.car_id')->join('company cr','cr.company_id = c.company_id','left')->where('cr.company_name','like',"%$company%");

            $refuel->alias('m')->join('car c','c.car_id = m.car_id')->join('company cr','cr.company_id = c.company_id','left')->where('cr.company_name','like',"%$company%");
            $service = $service->alias('m')->join('car c','c.car_id = m.car_id')->join('company cr','cr.company_id = c.company_id','left')->where('cr.company_name','like',"%$company%");
            $survey = $survey->alias('m')->join('car c','c.car_id = m.car_id')->join('company cr','cr.company_id = c.company_id','left')->where('cr.company_name','like',"%$company%");
            $insure = $insure->alias('m')->join('car c','c.car_id = m.car_id')->join('company cr','cr.company_id = c.company_id','left')->where('cr.company_name','like',"%$company%");
            $order = $order->alias('m')->join('car c','c.car_id = m.car_id')->join('company cr','cr.company_id = c.company_id','left')->where('cr.company_name','like',"%$company%");

        } elseif($where) {
            $car->where($where);
            $refuel->alias('m')->join('car c','c.car_id = m.car_id')->where($where);
            $service->alias('m')->join('car c','c.car_id = m.car_id')->where($where);
            $survey->alias('m')->join('car c','c.car_id = m.car_id')->where($where);
            $insure->alias('m')->join('car c','c.car_id = m.car_id')->where($where);
            $order->alias('m')->join('car c','c.car_id = m.car_id')->where($where);
        }


        $refuels = $refuel->where('km_add','>',0)->fetchSql(0)->select();
        $services = $service->select();

        //统计
        $count['total'] = Db::name('car')->count();
        $count['all'] = $car->count();
        $count['bind'] = $driver->where('m.car_id','>',0)->count();
        //百公里
        $count['km'] = array_sum( array_column($refuels,'km_add') );
        $count['amount'] = array_sum( array_column($refuels,'price') );
        $count['fuel'] = array_sum( array_column($refuels,'litre') );

        $count['wear'] = CxFuel( $count['fuel'],$count['km'] );
        $count['cost'] = CxFuel( $count['amount'],$count['km'] );

        //维修记录
        $count['service_times'] = count($services);
        $count['service_amount']= array_sum( array_column($services,'price') );

        //年检
        $count['survey']= $survey->sum('price');
        //加油
        $count['refuel']= count($refuels);
        $count['insure']= $insure->sum('policy_charge');

        //
        $count['beidou'] = Db::name('car')->where('is_beidou',1)->count();

        $this->assign('item',$count);
        return $this->out();
    }

    //车辆详情
    public function detail() {

        if($car_audit_id = input('param.car_audit_id')){
            $id = Db::name('car_audit')->where('car_audit_id',$car_audit_id)->value('car_id');

        }
        else{
            $id = input('param.car_id');
        }


        //车辆详情
        $item = Db::name('car')->alias('c')->join('CarRental r','c.company_id = r.company_id', 'left')->join('CarType t','c.car_type_id = t.car_type_id', 'left')->field('c.*,r.name AS company_name,t.*')->find($id);

        $item['service'] = Db::name('maintenance_record')->where('car_id',$id)->order('end_date DESC')->select();
        $item['refuel'] = Db::name('refuel_record')->where('car_id',$id)->order('start_date DESC')->select();
        $item['survey'] = Db::name('mot_record')->where('car_id',$id)->order('start_date DESC')->select();
        $item['insure'] = Db::name('car_insure')->where('car_id',$id)->order('start_date DESC')->select();
        //
        $item['mileage'] = intval($item['refuel'][0]['km']);


        //最新保险
        $this->assign('energy_types',config('base.energy_types'));
        $this->assign('sources',config('base.sources'));
        $this->assign('structures',config('base.structures'));
        $this->assign('gearbox_types',config('base.gearbox_types'));

        //
        foreach($item['insure'] AS $in) {
            if(!$item['insure_1'] && $in['policy_type'] == 1) {
                $item['insure_1'] = $in;
            }
            if(!$item['insure_2'] && $in['policy_type'] == 2) {
                $item['insure_2'] = $in;
            }
        }

        $this->assign('item',$item);

        return $this->out();

    }

	//品牌，车系，车型
	public function brands() {
		
		$id = input('param.id/d');
		$car_brands = Db::name('car_brand')->where('parent_id',$id)->fetchSql(0)->column('name','car_brand_id');
		
		return TplOptions($car_brands);
		
	}
	
	
	//通用选项
	protected function options($item = []) {
		//
		//公务只能看公务车型
		$where = [];
		if( $this->user['official'] ){
			$where['type'] = ['in','2,3'];
		}
//		$car_types = Cache::remember('car_types',function(){
        $car_types = Db::name('CarType')->where($where)->whereNull('delete_time')->where('state',1)->select();
//			return $car_types;
//		});

        $this->assign('car_types',array_column($car_types,'car_type_name','car_type_id'));
        $this->assign('car_type_ids',TplOptions($car_types,$item['car_type_id'],'car_type_name','car_type_id'));

        //品牌
        $car_brands = Cache::remember('car_brands',function(){
            $car_brands = Db::name('car_brand')->where('level',1)->column('CONCAT(`type`,`name`) AS name','car_brand_id');
            return $car_brands;
        });
        //车型
        $car_models = [];
        if($item['car_brand_id']) {
            $car_models = Db::name('car_brand')->where('parent_id',$item['car_brand_id'])->fetchSql(0)->column('name','car_brand_id');
        } else {
            $car_models = Cache::remember('car_models',function(){
                $car_models = Db::name('car_brand')->where('level',2)->column('name','car_brand_id');
                return $car_models;
            });
        }
        //系列
        $car_seriess = [];
        if($item['car_model_id']) {
            $car_series = Db::name('car_brand')->where('parent_id',$item['car_model_id'])->fetchSql(0)->column('name','car_brand_id');
        } else {
            $car_series = Cache::remember('car_series',function(){
                $car_series = Db::name('car_brand')->where('level',3)->column('name','car_brand_id');
                return $car_series;
            });
        }
        //公司
        if($item['company_id']) {
            $item['company_name'] = Db::name('company')->where('company_id',$item['company_id'])->fetchSql(0)->value('company_name');
        }//委托公司
        if($item['entrust_company_id']) {
            $item['entrust_company_name'] = Db::name('company')->where('company_id',$item['entrust_company_id'])->fetchSql(0)->value('company_name');
        }

        if($item['car_type_id']) {
            $car_type = Db::name('car_type')->where('car_type_id',$item['car_type_id'])->fetchSql(0)->find();
            $item['car_type'] = CxCarTypeTitle($car_type)['title'];
        }


        $entrust = $this->_entrust();

        //车辆性质
        $prop = config('base.car_prop');
        $props = $item['prop'] ? explode(',',$item['prop']) : [];
        foreach($prop AS $i => $p) {
            $prop[$i]['open'] = true;
            if($props && in_array($p['id'],$props)) $prop[$i]['checked'] = true;
        }
        $this->assign('props',json_encode($prop));

        //区域
        $area_ids = Db::name('area')->select();
//		$area_ids = Arr2Sibling($area_ids,0,0,'area_id','area_pid');
        $this->assign('area_ids',TplOptions($area_ids,$item['area_pid'],'area_name','area_id'));

        //下拉选项
        $this->assign('car_brands',$car_brands);
        $this->assign('car_brand_ids',TplOptions($car_brands,$item['car_brand_id']));
        $this->assign('car_models',$car_models);
        $this->assign('car_model_ids',TplOptions($car_models,$item['car_model_id']));
        $this->assign('car_series',$car_series);
        $this->assign('car_series_ids',TplOptions($car_series,$item['car_series_id']));
        $this->assign('energy_types',TplOptions(config('base.energy_types'),$item['energy_type']));
        $this->assign('sources',TplOptions(config('base.sources'),$item['source']));
        $this->assign('structures',TplOptions(config('base.structures'),$item['structure']));
        $this->assign('gearbox_types',TplOptions(config('base.gearbox_types'),$item['gearbox_type']));

        return $item;
    }

    //
    public function entrust() {

        $entrust = $this->_entrust();
        $this->assign('entrust',$entrust);

        return $this->popup();
    }
    //
    protected function _entrust() {
        //委托车辆
        $company_ids = Db::name('car')->distinct(true)->where('entrust_company_id','>',0)->whereNull('delete_time')->group('company_id')->column('company_id');

        $entrust = [];
        if($company_ids) {
            //所有公司
            $companys = Db::name('company')->whereIn('company_id',$company_ids)->column('company_name','company_id');
            foreach($companys AS $er => $name) {
                $entrust[] = $value = [
                    'name' => $name,
                    'count' => Db::name('car')->where('company_id',$er)->whereNull('delete_time')->count(),
                    'id' => $er,
                ];
            }

            $entrust_company = input('param.entrust_company');
            $entrust_company && $where['company_id'] = $entrust_company;
            $this->assign('entrust_companys',TplOptions($companys,$entrust_company));

        }
        $entrust = $this->multisort($entrust,'count');

        return $entrust;
    }

    protected function multisort($arr,$keys,$type='desc') {
        $keysvalue = $new_array = array();
        foreach ($arr as $k=>$v){
            $keysvalue[$k] = $v[$keys];
        }
        if($type == 'asc'){
            asort($keysvalue);
        }else{
            arsort($keysvalue);
        }
        reset($keysvalue);
        foreach ($keysvalue as $k=>$v){
            $new_array[$k] = $arr[$k];
        }
        return $new_array;
    }

    //新增购置车辆
    public function audit_add()
    {
        $file = request()->file('front_img');
        if($file) {
            $P['front_img'] = $file->move(UPLOAD_PATH);
        }
        $file = request()->file('back_img');
        if($file) {
            $P['back_img'] = $file->move(UPLOAD_PATH);
        }
        $file = request()->file('side_img');
        if($file) {
            $P['side_img'] = $file->move(UPLOAD_PATH);
        }
        $file = request()->file('engine_img');
        if($file) {
            $P['engine_img'] = $file->move(UPLOAD_PATH);
        }
        $file = request()->file('business_policy_img');
        if($file) {
            $P['business_policy_img'] = $file->move(UPLOAD_PATH);
        }
        $file = request()->file('compulsory_policy_img');
        if($file) {
            $P['compulsory_policy_img'] = $file->move(UPLOAD_PATH);
        }
        $file = request()->file('driving_license_img');
        if($file) {
            $P['driving_license_img'] = $file->move(UPLOAD_PATH);
        }
        $file = request()->file('driving_license_img2');
        if($file) {
            $P['driving_license_img2'] = $file->move(UPLOAD_PATH);
        }

        $P = input('param.');
        $data = [];
        $date = date('Y-m-d H:i:s');

        $P['car_type_id'] && $data['car_type_id'] = $P['car_type_id'];
        $P['area_id'] && $data['area_id'] =  $P['area_id'];
        $P['brand_name'] && $data['brand_name'] = $P['brand_name'];
        $P['car_brand_id'] && $data['car_brand_id'] = $P['car_brand_id'];
        $P['car_model_id'] && $data['car_model_id'] = $P['car_model_id'];
        $P['car_series_id'] && $data['car_series_id'] = $P['car_series_id'];
        $P['company_id'] && $data['company_id'] =  $P['company_id'];
        $P['car_use_id'] && $data['car_use_id'] =  $P['car_use_id'];
        $P['entrust_company_id'] && $data['entrust_company_id'] =  $P['entrust_company_id'];
        $P['entrust_rental_id'] && $data['entrust_rental_id'] =  $P['entrust_rental_id'];
        $P['entrust_use_id'] && $data['entrust_use_id'] =  $P['entrust_use_id'];
        $P['is_beidou'] && $data['is_beidou'] =  $P['is_beidou'];
        $P['from_id'] && $data['from_id'] =  $P['from_id'];
        $P['number'] && $data['number'] =  $P['number'];
        $P['source'] && $data['source'] =  $P['source'];
        $P['structure'] && $data['structure'] =  $P['structure'];
        $P['colour'] && $data['colour'] =  $P['colour'];
        $P['gearbox_type'] && $data['gearbox_type'] =  $P['gearbox_type'];
        $P['displacement'] && $data['displacement'] =  $P['displacement'];
        $P['car_age'] && $data['car_age'] =  $P['car_age'];
        $P['energy_type'] && $data['energy_type'] =  $P['energy_type'];
        $P['engine_no'] && $data['engine_no'] =  $P['engine_no'];
        $P['chassis_no'] && $data['chassis_no'] =  $P['chassis_no'];
        $P['vin'] && $data['vin'] =  $P['vin'];
        $P['carry'] && $data['carry'] =  $P['carry'];
        $P['buy_date'] && $data['buy_date'] =  $P['buy_date'];
        $P['buy_money'] && $data['buy_money'] =  $P['buy_money'];
        $P['mileage'] && $data['mileage'] =  $P['mileage'];
        $P['latitude'] && $data['latitude'] =  $P['latitude'];
        $P['longitude'] && $data['longitude'] =  $P['longitude'];
        $P['car_state'] && $data['car_state'] =  $P['car_state'];
        $P['driving_license_issued'] && $data['driving_license_issued'] =  $P['driving_license_issued'];
        $P['driving_license_effective'] && $data['driving_license_effective'] =  $P['driving_license_effective'];
        $P['prop'] && $data['prop'] =  $P['prop'];
        $data['state'] =  '9';
        $P['driving_license_img'] && $data['driving_license_img'] =  $P['driving_license_img'];
        $P['driving_license_img2'] && $data['driving_license_img2'] =  $P['driving_license_img2'];
        $P['front_img'] && $data['front_img'] =  $P['front_img'];
        $P['back_img'] && $data['back_img'] =  $P['back_img'];
        $P['side_img'] && $data['side_img'] =  $P['side_img'];
        $P['engine_img'] && $data['engine_img'] =  $P['engine_img'];
        $P['business_insurance_company'] && $data['business_insurance_company'] =  $P['business_insurance_company'];
        $P['business_policy_no'] && $data['business_policy_no'] =  $P['business_policy_no'];
        $P['business_policy_effective'] && $data['business_policy_effective'] = $P['business_policy_effective'];
        $P['phone'] && $data['phone'] = $P['phone'];
        $P['rent_company'] && $data['rent_company'] =  $P['rent_company'];
        $P['business_policy_img'] && $data['business_policy_img'] =  $P['business_policy_img'];
        $P['compulsory_policy_no'] && $data['compulsory_policy_no'] =  $P['compulsory_policy_no'];
        $P['compulsory_policy_effective'] && $data['compulsory_policy_effective'] =  $P['compulsory_policy_effective'];
        $P['compulsory_policy_img'] && $data['compulsory_policy_img'] =  $P['compulsory_policy_img'];
        $data['register_time'] =  $date;
        $P['delete_time'] && $data['delete_time'] =  $P['delete_time'];
        Db::name('car')->insert($data);
        $car_id = Db::name('car')->getLastInsID();
        $car_audit_return = Db::name('car_audit')->where('car_audit_id',$P['car_audit_id'])->update(['state' => '4','car_id' => $car_id,'4_date' => $date]);
        if($car_id && $car_audit_return){
            $data = array(
                'code' => '1',
                'msg' => ''
            );
            $this->redirect('Car/audit');
        }
    }

    //新购置车辆审核
    public function audit_ok()
    {
        $date = date('Y-m-d H:i:s');
        $car_audit_id = input('param.car_audit_id');
        Db::name('car_audit')->where('car_audit_id',$car_audit_id)->update(['state' => '5','5_date' => $date]);
        $car_id = Db::name('car_audit')->where('car_audit_id',$car_audit_id)->value('car_id');
        Db::name('car')->where('car_id',$car_id)->update(['state' => '1']);
        $data = array(
            'code' => '1',
            'msg' => ''
        );
        return json($data);
    }
}
